package com.practice;

import java.util.List;
import java.util.ArrayList;

import com.practice.retry.ObjectWithExceptionRetryTask;
import com.practice.retry.ObjectWithExceptionRetryWorker;
import com.practice.retry.VoidWithExceptionRetryTask;
import com.practice.retry.RetryWorker;
import com.practice.retry.IntegerWithoutExceptionRetryWorker;
import com.practice.retry.VoidWithExceptionRetryWorker;

public class RetryPractice implements IPractice {

	private List<Integer> list;
	
	@Override
	public void run() {
		
		 list = new ArrayList<>(5);
		 list.add(-1);
		 list.add(-5);
		 list.add(-3);
		 list.add(5);
		
		ObjectWithExceptionRetryWorker retryWorker = new ObjectWithExceptionRetryWorker();
		retryWorker.setMaxRetryCount(10);
		retryWorker.setSleepMilliseconds(10);
		
		ObjectWithExceptionRetryTask task = new ObjectWithExceptionRetryTask() {
			
			@Override
			public Object run() throws Exception {
				return retrieveValue();
			}
		};
		
		retryWorker.start(task, "Get value.");
		Integer value = (Integer)task.getResult();
		
		System.out.println(value);
		System.out.println(task.isSuccess());
	}
	
	@SuppressWarnings("unused")
	private int doReturnWork() {
		if (list.size() > 0) {
			int result = list.get(0);
			list.remove(0);
			return result;
		} else {
			return -1;
		}
	}
	
	@SuppressWarnings("unused")
	private void doExceptionWork() throws Exception {
		if (list.size() > 0) {
			int result = list.get(0);
			list.remove(0);
			if (result != 0) {
				throw new Exception(Integer.toString(result));
			}
		} else {
			throw new IndexOutOfBoundsException();
		}
	}
	
	private Integer retrieveValue() throws Exception {
		if (list.size() > 0) {
			Integer value = list.get(0);
			list.remove(0);
			if (value < 0) {
				throw new Exception();
			}
			
			return value;
		} else {
			throw new IndexOutOfBoundsException();
		}
	}
}